<div class="container">
  <input type="hidden" id="topic-id" value="<%= typeof(topicId) !== 'undefined' ? topicId : '' %>"/>
  <input type="hidden" id="zone-object" value="<%= typeof(zone) !== 'undefined' ? JSON.stringify(zone) : '' %>"/>
  <div class="col-md-4">
    <div class="panel panel-default">
      <div class="panel-heading">
        宣传图
        <div class="pull-right">
        <a v-on:click="onUploadImage">上传</a>
        •
        <a v-on:click="onDeleteImage"> 删除</a>
        </div>
      </div>
      <div class="panel-body">
          <a href="#" class="thumbnail" v-if="advertisingMap" v-cloak>
            <img v-bind:src="advertisingMap">
          </a>
          <p v-else>没有图</p>
      </div>
    </div>

    <% if(typeof(zone) !== 'undefined' && zone && zone.audioAttachment) {%>
    <div class="panel panel-default">
      <div class="panel-heading">
        音频附件
      </div>
      <div class="panel-body">
        <div class="list-group">
          <a href="#" class="list-group-item" v-for="(index, item) in audioList">
            <button class="btn btn-sm btn-danger pull-right" v-on:click="onDeleteAudio(index)">删除</button>
            <h4 class="list-group-item-heading">{{ item.title }}</h4>
            <p class="list-group-item-text">{{ item.describe }}</p>
            <p class="list-group-item-text">{{ item.url }}</p>
          </a>
        </div>

        <div class="form-group">
          <button class='btn btn-primary' v-on:click="onShowAudioDialog">选择音频</button>
        </div>
      </div>
    </div>
    <% } %>
  </div>
  <div class="col-md-8">
    <div class="panel panel-default">
      <div class="panel-heading">
        <div class="panel-title" v-if="pageTitle" v-cloak>{{ pageTitle }}</div>
      </div>
      <div class="panel-body">
        <div class="form-group" v-if="menus && menus.length > 0" v-cloak>
          <select class="form-control" v-on:change="onSelectedMenu($event)" v-model="selectedMenu">
            <option v-for="menu in menus" v-bind:value="menu.key">
            {{ menu.value }}
            </option>
          </select>
        </div>

        <div class="form-group" v-if="submenus && submenus.length > 0" v-cloak>
          <select class="form-control" v-model="selectedSubmenu">
            <option v-for="submenu in submenus" v-bind:value="submenu.key">
            {{ submenu.value }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <input autofocus type="text" class="form-control" id='title' name='title' placeholder="标题字数 10 字以上" v-model="title">
        </div>

        <div class="form-group">
          <ul id="topicTags">
          </ul>
        </div>

        <div class='markdown_editor in_editor'>
          <div class='markdown_in_editor'>
            <textarea class='form-control editor' name='t_content' rows='20' placeholder='支持 Markdown 语法'></textarea>
          </div>
        </div>
        <button class='btn btn-primary' v-if="zoneObj.mustReview" v-on:click="onSave()">保存</button>
        <button class='btn btn-primary' v-else v-on:click="onSave('reviewed')">保存</button>
        <% if(typeof(csrf) !== 'undefined') {%>
        <input type='hidden' name='_csrf' value='<%= csrf %>'>
        <% } %>
        <button class='btn btn-primary' v-if="zoneObj.mustReview" v-on:click="onReviewing">提交审核</button>
        <button type="button" class="btn btn-primary pull-right" v-on:click="onPreview">预览</button>
        <input type="checkbox" id="isHtml" v-model="isHtml">
        <label for="checkbox">html编辑模式</label>
      </div>
    </div>
  </div>
</div>
<!-- Modal -->
<div class="modal fade previewDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">预览</h4>
      </div>
      <div class="modal-body">
        <div id="preview-content" class='<%=config.mdType%>-body content preview-content'>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade audio-list-dialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">预览</h4>
      </div>
      <div class="modal-body">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>分类</th>
              <th>标题</th>
              <th>描述</th>
              <th>链接</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="previewAudioList.length > 0" v-for="(index, item) in previewAudioList">
              <td style="width: 60px">{{ item.type }}</td>
              <td style="width: 80px">{{ item.title }}</td>
              <td style="width: 80px">{{ item.describe }}</td>
              <td style="width: 120px">{{ item.url }}</td>
              <td style="width: 20px">
                <div class="btn-group disabled">
                  <button type="button" class="btn btn-default dropdown-toggle btn-sm" v-on:click="onSelectAudio(index)">
                    选择
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<!-- markdown editor -->
<%- partial('../../includes/editor') %>
<script>
  var appId = $('[name=app-id]').val();
  var zoneObjString = $('#zone-object').val();
  var zoneObj = zoneObjString ? JSON.parse(zoneObjString) : {};
  var sampleTags = [];

  $('#topicTags').tagit({
      availableTags: sampleTags,
      removeConfirmation: true,
      itemName: 'item',
      fieldName: 'tags'
  });
  var topicId = $('#topic-id').val();

  var pagePrefix = '<%= apiPrefix.page %>';
  var dataPrefix = '<%= apiPrefix.data %>';
  var submitUrl = dataPrefix + '/zone/' + zoneObj.key + '/' + zoneObj.template + '/topic/' + topicId + '/edit';


  var editor = new Editor();
  editor.render($('.editor')[0]);

  var vue = new Vue({
    el: '#app',
    data: {
      zoneObj: {},
      topicId: '',
      title: '',
      advertisingMap: '',
      pageTitle: '编辑',
      topic: '',
      menus: [],
      selectedMenu: '',
      submenus: [],
      selectedSubmenu: '',
      isHtml: false,
      audioList: [],
      errorMsg: '',
      successMsg: '',
      // audio data
      previewAudioList: [],
      currentPage: 0,
      pages: 0,
    },
    methods: {
      getMenus: function() {
        $.post(dataPrefix + '/menu/data', {appId: appId, zoneId: vue.zoneObj._id, all: true}, function(result) {
          if (result.error) {
            vue.errorMsg = result.error;
          } else {
            let data = result.data || [];

            vue.menus = data;
            vue.updateSubmenusOptions(vue.selectedMenu);
          }
        });
      },
      onSelectedMenu: function(event) {
        vue.updateSubmenusOptions(event.target.value);
      },
      updateSubmenusOptions: function(key) {
        let index = _.findIndex(vue.menus, function(menu) {
            return menu.key === key;
        });

        if (vue.menus.length > 0 && vue.menus[index]) {
          vue.submenus = vue.menus[index].submenus || [];
        }

        // TODO 洗数据用
        if (vue.submenus.length < 1) {
          vue.selectedSubmenu = '';
        }
      },
      updateAudioList: function(data) {
        console.log(data)
        data.forEach( function(item){
          vue.audioList.push(item)
        });
      },
      getTopic: function() {
        $.post(dataPrefix + '/topic/' + this.topicId + '/data', {appId: appId}, function (result) {
          if (result.err) {
            vue.errorMsg = result.err;
          } else {
            vue.topic = result.data || {};
            vue.zoneObj._id = vue.topic.zoneId || '';
            vue.selectedMenu = vue.topic.menu || '';
            vue.selectedSubmenu = vue.topic.submenu || '';
            vue.title = vue.topic.title || '';
            vue.advertisingMap = vue.topic.advertisingMap || '';
            vue.tags = vue.topic.tags && vue.topic.tags !== '' ? vue.topic.tags.split(',') : [];
            vue.isHtml = vue.topic.isHtml;
            editor.codemirror.setValue(vue.topic.content || '');
            vue.getMenus();
            updateTags(vue.tags);
            vue.updateAudioList(vue.topic.audioList);
          }
        });
      },
      onSave: function(status) {
        vue.errorMsg = ''
        if (vue.title === '') {
          vue.errorMsg = '标题为空';
          return;
        }

        if (editor.codemirror.getValue() === '') {
          vue.errorMsg = '内容为空'
          return
        }

        $.post(submitUrl, {
          appId: appId,
          _csrf: $('#_csrf').val(),
          zoneId: vue.zoneObj._id,
          title: vue.title,
          advertisingMap: vue.advertisingMap,
          selectedSubmenu: vue.selectedSubmenu,
          menu: vue.selectedMenu,
          submenu: vue.selectedSubmenu,
          content: editor.codemirror.getValue(),
          tags: getTags(),
          isHtml: vue.isHtml,
          audioList: vue.audioList,
          status: status? status : 'saved'},
          function (result) {
            if (result.err) {
              vue.errorMsg = result.err;
            } else {
              location.href = result.url;
            }
        });
      },
      onReviewing: function() {
        if (vue.selectedMenu === '' || vue.title === '') {
          vue.errorMsg = '有内容为空';
          return;
        }

        $.post(submitUrl, {
          appId: appId,
          _csrf: $('#_csrf').val(),
          zoneId: vue.zoneObj._id,
          title: vue.title,
          advertisingMap: vue.advertisingMap,
          selectedSubmenu: vue.selectedSubmenu,
          menu: vue.selectedMenu,
          submenu: vue.selectedSubmenu,
          content: editor.codemirror.getValue(),
          tags: getTags(),
          audioList: vue.audioList,
          status: 'reviewing'},
          function (result) {
            if (result.err) {
              vue.errorMsg = result.err;
            } else {
              location.href = result.url;
            }
        });
      },
      onPreview: function() {
        var md = new markdownit()
        $('div#preview-content').empty()
        $('div#preview-content').append(md.render(editor.codemirror.getValue()))
        $('.previewDialog').modal('show')
      },
      onUploadImage: function() {
        var imageUpload = new ImageUpload();
        imageUpload.bind(uploadImageCallback);
      },
      onDeleteImage: function() {
        vue.advertisingMap = '';
      },
      onAddAudio: function() {
        if (vue.audioLabel !== '' && vue.audioUrl !== '') {
          vue.audioList.push({label: vue.audioLabel, url: vue.audioUrl})
          vue.audioLabel = '';
          vue.audioUrl = '';
        }
      },
      onDeleteAudio: function(index) {
        vue.audioList.$remove(vue.audioList[index]);
      },
      onShowAudioDialog: function() {
        $('.audio-list-dialog').modal('show');
        vue.getPreviewAudio();
      },
      onSelectAudio: function(index) {
        // $('.audio-list-dialog').modal('hidden');
        var audio = vue.previewAudioList[index];
        vue.audioList.push(audio);
      },
      getPreviewAudio: function() {
        $.post(dataPrefix + '/audio/data', {appId: appId}, function(result) {
          if(result.err) {
            vue.errorMsg = result.err;
          } else {
            var data = result.data && result.data.length > 0 ? result.data : [];

            data.forEach( function(item){
              vue.previewAudioList.push(item)
            });
          }
        });
      }
    }
  });

  function uploadImageCallback(url) {
    vue.advertisingMap = url;
  }

  function getTags() {
    var tags = [];
    $("input[name='tags']").each(function(index,item) {
      tags.push($(this).val())
    });

    return tags;
  }

  function updateTags(tags) {
    tags.forEach(item => {$("#topicTags").tagit("createTag", item)})
  }

  vue.topicId = topicId;
  vue.pageTitle = '编辑';
  vue.getTopic();
</script>
